package com.guit.hrms.controller;

import com.guit.hrms.dto.RoleDTO;
import com.guit.hrms.po.utilsPO.Result;
import com.guit.hrms.service.RoleService;
import com.guit.hrms.vo.RoleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/api/roles")
public class RoleController {
    @Autowired
    private RoleService roleService;

    /**
     * 查询角色和权限
     * @return 角色和权限信息
     */
    @GetMapping
    public Result queryRole(){
        RoleVO roleVO = roleService.queryRole();
        return Result.success(roleVO);
    }

    /**
     * 添加角色
     * @param roleDTO 角色信息
     * @return 添加结果
     */
    @PostMapping
    public Result addRole(@RequestBody RoleDTO roleDTO){
        if (roleDTO.getName() == null || roleDTO.getDescription() == null || roleDTO.getPermissions() == null || roleDTO.getApis() ==null){
            return Result.error("参数错误");
        }else {
            Integer result = roleService.addRole(roleDTO);
            if (result == 0){
                return Result.error("角色已存在");
            } else {
                return Result.success();
            }
        }
    }

    /**
     * 修改角色
     * @param roleDTO 角色信息
     * @return 修改结果
     */
    @PatchMapping
    public Result updateRole(@RequestBody RoleDTO roleDTO){
        if (roleDTO.getId() == null && ( roleDTO.getName() == null || roleDTO.getDescription() == null || roleDTO.getPermissions() == null)){
            return Result.error("参数错误");
        }else {
            Integer result = roleService.updateRole(roleDTO);
            if (result == 0){
                return Result.error("角色修改失败");
            } else {
                return Result.success();
            }
        }
    }

    /**
     * 删除角色
     * @param roleIds 角色id列表
     * @return 删除结果
     */
    @DeleteMapping("/{roleIds}")
    public Result deleteRole(@PathVariable List<Integer> roleIds){
        if (roleIds.isEmpty()){
            return Result.error("参数错误");
        } else {
            Integer result = roleService.deleteRole(roleIds);
            if (result == 0){
                return Result.error("角色删除失败");
            } else {
                return Result.success();
            }
        }
    }
}
